package com.wx.leetcode;

import java.util.Arrays;

/**
 * @ClassName SpiralOrderTopic
 * @Author wx
 * @Description 顺时针打印矩阵
 * 输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字。
 * 输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
 * 输出：[1,2,3,6,9,8,7,4,5]
 * @Date 2020-04-12-11:23
 */
public class SpiralOrderTopic {

    public static int[] spiralOrder(int[][] matrix) {
        int n = matrix.length;
        if (n == 0) {
            return new int[0];
        }

        if (n == 1) {
            return matrix[0];
        }
        int m = matrix[0].length;
        //计算逻辑数组长度
        int totalLength = n * m;
        //二维数组最后下标
        int endIndex = m - 1;
        int[] temp = new int[totalLength];

        for (int i = 0, j = 0; i < totalLength; i++) {
            //计算一维数组下标
            int index = j / m;
            //计算二维数组下标
            int index2 = j % m;

            if (index == n - 1) {
                temp[i] = matrix[index][index2];
                j = index2 == 0 ? m : --j;

            } else {
                temp[i] = matrix[index][index2];
                j = index2 == endIndex ? j + m : ++j;
            }
        }
        return temp;
    }

    public static int[] spiralOrderV2(int[][] matrix) {
        if(matrix.length == 0) return new int[0];
        int l = 0, r = matrix[0].length - 1, t = 0, b = matrix.length - 1, x = 0;
        int[] res = new int[(r + 1) * (b + 1)];
        while(true) {
            for(int i = l; i <= r; i++) res[x++] = matrix[t][i]; // left to right.
            if(++t > b) break;
            for(int i = t; i <= b; i++) res[x++] = matrix[i][r]; // top to bottom.
            if(l > --r) break;
            for(int i = r; i >= l; i--) res[x++] = matrix[b][i]; // right to left.
            if(t > --b) break;
            for(int i = b; i >= t; i--) res[x++] = matrix[i][l]; // bottom to top.
            if(++l > r) break;
        }
        return res;
    }

    public static void main(String[] agrs) {
        int[][] matrix = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        System.out.println(Arrays.toString(spiralOrderV2(matrix)));
    }
}
